<!--
*Author：jxx
 *Contact：283591387@qq.com
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/mall/Member_coupon_his.js此处编写
 -->
<template>
  <div>
    <!-- 批量发券 -->
    <VolBox :model.sync="model" title="发券" :width="800" :height="500">
      <VolForm
        ref="myform"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields"
        :formRules="formRules"
      ></VolForm>
      <div class="volTable">
        <VolTable
          ref="editTable1"
          :columns="columns"
          :max-height="270"
          :index="true"
          :tableData="tableData"
          :ck="false"
        ></VolTable>
      </div>
      <VolForm
        ref="myform2"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields2"
        :formRules="formRules2"
      ></VolForm>
      <div class="HYCl" v-show="HYStatus">
        <el-upload
          class="upload-demo"
          action=""
          :on-change="handleChange"
          :show-file-list="false"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">导入</el-button>
        </el-upload>
        <el-button size="small" type="primary" @click="downLOading"
          >下载模板</el-button
        >
        <VolTable
          ref="editTable2"
          :columns="columns2"
          :max-height="270"
          :index="true"
          :tableData="tableData2"
          :ck="false"
        ></VolTable>
      </div>
      <div slot="footer">
        <Button type="default" @click="submit">确认</Button>
      </div>
    </VolBox>
    <!-- 发券  -->
    <VolBox :model.sync="model3" title="发券" :width="600" :height="300">
      <VolForm
        ref="myform3"
        :loadKey="true"
        :formFields="formFields3"
        :formRules="formRules3"
      ></VolForm>
      <div slot="footer">
        <Button type="default" @click="submit3">确认</Button>
      </div>
    </VolBox>
    <!-- 延期 -->
    <VolBox :lazy="true" :model.sync="model6" title="延期">
      <VolForm
        ref="myform6"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields6"
        :formRules="formRules6"
      ></VolForm>
      <div slot="footer">
        <Button type="default" @click="submit6">确认</Button>
        <Button type="default" @click="model6 = false">关闭</Button>
      </div>
    </VolBox>
    <VolBox :lazy="true" :model.sync="model7" title="手工核销">
      <VolForm
        ref="myform7"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields7"
        :formRules="formRules7"
      ></VolForm>
      <div slot="footer">
        <Button type="default" @click="submit7">确认</Button>
        <Button type="default" @click="model7 = false">关闭</Button>
      </div>
    </VolBox>
    <VolBox :lazy="true" :model.sync="model8" title="作废">
      <VolForm
        ref="myform7"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields8"
        :formRules="formRules8"
      ></VolForm>
      <div slot="footer">
        <Button type="default" @click="submit8">确认</Button>
        <Button type="default" @click="model8 = false">关闭</Button>
      </div>
    </VolBox>
    <VolBox
      :lazy="true"
      :model.sync="model9"
      title="分配"
      :width="800"
      :height="500"
    >
      <VolForm
        ref="myform4"
        :label-width="100"
        :loadKey="true"
        :formFields="formFields4"
        :formRules="formRules4"
      ></VolForm>
      <div class="xxx-box">
        <!-- 表格 -->
        <div class="all-check">
          <el-checkbox v-model="pageChecked"
            >跨页全选(不允许自定义)</el-checkbox
          >
        </div>
        <el-table
          :data="tableData4"
          ref="mListTable"
          @select="changeSelect"
          @select-all="selectAll"
          height="500"
        >
          <el-table-column type="index" width="55"> </el-table-column>
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="coupon_make_name" label="制券名称" width="180">
          </el-table-column>
          <el-table-column prop="couponid" label="优惠券id" width="180">
          </el-table-column>
          <el-table-column prop="couponcode" label="优惠券模板" width="100">
            <template slot-scope="scope">
              <span>{{ getText(couponcodeList, scope.row.couponcode) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="use_status" label="使用状态" width="100">
            <template slot-scope="scope">
              <span>{{ getText(use_statusList, scope.row.use_status) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="100">
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间" width="100">
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="all-el-page">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="queryParamsPage"
            :page-size="1000"
            layout="total, prev, pager, next, jumper"
            :total="fyTotal"
          >
          </el-pagination>
        </div>
      </div>
      <div slot="footer">
        <Button type="default" @click="submit9">确认</Button>
        <Button type="default" @click="model9 = false">关闭</Button>
      </div>
    </VolBox>
  </div>
</template>

<script>
import VolBox from "@/components/basic/VolBox.vue";
import VolForm from "@/components/basic/VolForm.vue";
import VolTable from "@/components/basic/VolTable.vue";
import XLSX from "xlsx";
const tableToNotIE = (function() {
  // 编码要用utf-8不然默认gbk会出现中文乱码
  let uri = "data:application/vnd.ms-excel;base64,",
    template =
      '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
    },
    format = (s, c) => {
      return s.replace(/{(\w+)}/g, (m, p) => {
        return c[p];
      });
    };
  return (table, name) => {
    let ctx = {
      worksheet: name,
      table
    };

    //创建下载
    let link = document.createElement("a");
    link.setAttribute("href", uri + base64(format(template, ctx)));

    link.setAttribute("download", name);

    link.click();
  };
})();
export default {
  components: {
    VolBox,
    VolForm,
    VolTable
  },
  data() {
    return {
      model: false,
      formFields: { preparation: "", cardtype: "" },
      formRules: [
        [
          {
            title: "选择制券",
            field: "preparation",
            type: "selectList",
            dataKey: "",
            data: [],
            colSize: 6
          }
        ]
      ],
      columns: [
        {
          field: "coupon_batch",
          title: "批号",
          type: "int",
          width: 100,
          align: "left",
          sortable: true
        },
        {
          field: "status",
          title: "状态",
          type: "int",
          bind: { key: "MakeCoupon_Status", data: [] },
          width: 80,
          align: "left"
        },
        {
          field: "coupon_name",
          title: "券名称",
          type: "string",
          width: 100,
          align: "left"
        },
        {
          field: "coupon_count",
          title: "券数量",
          type: "int",
          width: 80,
          align: "left"
        },
        {
          field: "take_count",
          title: "已发券数量",
          type: "int",
          width: 100,
          align: "left"
        },
        {
          field: "coupon_note",
          title: "描述",
          type: "string",
          width: 120,
          align: "left"
        },
        {
          field: "creator",
          title: "创建人",
          type: "string",
          width: 120,
          align: "left"
        },
        {
          field: "createDate",
          title: "创建时间",
          type: "datetime",
          width: 120,
          align: "left",
          sortable: true
        }
      ],
      tableData: [],
      formFields2: { vpType: [], givetype: 0, cardtype: 0, textSpanz: "" },
      formRules2: [
        [
          {
            title: "分类",
            field: "givetype",
            type: "radio",
            data: [
              { key: 0, value: "会员类型" },
              { key: 1, value: "名单" },
              { key: 2, value: "卡" }
            ]
          }
          // {
          //   title: "",
          //   field: "textSpanz",
          //   type: "textSpan",
          //   cont: ['','张']
          // },
        ],
        [
          {
            title: "卡模板",
            field: "cardtype",
            type: "select",
            dataKey: "",
            data: [],
            colSize: 6,
            hidden: false
          }
        ],
        [
          {
            title: "会员类型",
            field: "vpType",
            type: "transfer",
            titles: ["未选会员类型", "已选会员类型"],
            data: [],
            colSize: 12,
            hidden: true
          }
        ]
      ],
      MebcouponMakeList: [],
      columns2: [
        {
          field: "namez",
          title: "姓名",
          type: "int",
          width: 120,
          align: "left"
        },
        {
          field: "phone",
          title: "手机号",
          type: "int",
          width: 100,
          align: "left"
        }
      ],
      tableData2: [],
      HYStatus: false,
      model3: false,
      formFields3: {
        phone: "",
        name: "",
        distributorCode: "",
        certificate_type: "",
        id_card: ""
      },
      formRules3: [
        [
          {
            title: "手机号",
            field: "phone",
            type: "phone",
            required: true
          },
          {
            render: (h, {}) => {
              return h(
                "button",
                {
                  class: "ivu-btn",
                  style: {
                    "margin-left": "10px"
                  },
                  on: {
                    click: () => {
                      let param = {
                        order: "desc",
                        page: 1,
                        rows: 30,
                        sort: "",
                        wheres: `[{\"name\":\"phone\",\"value\":\"${this.formFields3.phone}\",\"displayType\":\"text\"}]`
                      };
                      this.http
                        .post(
                          "/api/SmallUserArchives/GetSmallUserPageData",
                          param
                        )
                        .then(res => {
                          if (res.rows.length != 0) {
                            // 13463060925
                            this.formFields3.name = res.rows[0].name;
                            this.formFields3.distributorCode =
                              res.rows[0].distributorCode;
                            this.formFields3.certificate_type =
                              res.rows[0].certificate_type;
                            this.formFields3.id_card = res.rows[0].id_card;

                            this.HYZHSTATUS = false;
                          } else {
                            this.HYZHSTATUS = true;
                            this.$refs.myform4.reset();
                          }
                        });
                    }
                  }
                },
                "查询"
              );
            }
          }
        ],
        [
          {
            title: "姓名",
            field: "name",
            type: "text",
            required: true
          },
          {
            title: "分销商",
            field: "distributorCode",
            type: "select",
            dataKey: "distributorList",
            data: [],
            required: true
          }
        ],
        [
          {
            title: "证件类型",
            field: "certificate_type",
            type: "select",
            dataKey: "certificate_type",
            data: []
            // required: true,
          },
          {
            title: "证件号",
            field: "id_card",
            type: "text"
            // required: true,
          }
        ]
      ],
      FJGR: {},
      SGHX: {},
      HYZHSTATUS: false,
      model6: false,
      model7: false,
      model8: false,
      formFields6: { use_endtime: "" },
      formRules6: [],
      formFields7: { remark: "" },
      formRules7: [],
      formFields8: {
        remark: "",
        use_status: 5
      },
      formRules8: [],
      model9: false,
      formFields4: {
        opersqrorId: [],
        preparation: ""
      },
      formRules4: [
        [
          {
            title: "授权人",
            field: "opersqrorId",
            type: "transfer",
            titles: ["未选授权人", "选中授权人"],
            data: [],
            colSize: 12
          }
        ],
        [
          {
            title: "券模版",
            field: "preparation",
            type: "select",
            dataKey: "",
            data: []
          },
          {
            render: (h, {}) => {
              return h(
                "button",
                {
                  class: "ivu-btn",
                  style: {
                    "margin-left": "10px"
                  },
                  on: {
                    click: () => {
                      this.getMebCouponhis(this.formFields4.preparation);
                    }
                  }
                },
                "查询"
              );
            }
          }
        ]
      ],
      MebcouponHISList: [],
      columns4: [
        {
          field: "coupon_make_name",
          title: "制券名称",
          type: "int",
          width: 180,
          align: "left"
        },
        {
          field: "couponid",
          title: "优惠券id",
          type: "int",
          width: 110,
          align: "left",
          sortable: true
        },
        {
          field: "couponcode",
          title: "优惠券模板",
          type: "string",
          width: 100,
          align: "left",
          bind: { key: "", data: [] }
        },
        {
          field: "use_status",
          title: "使用状态",
          type: "int",
          width: 90,
          align: "left",
          bind: { key: "MebHisUseStatus", data: [] }
        },
        {
          field: "creator",
          title: "创建人",
          type: "string",
          width: 180,
          align: "left"
        },
        { field: "createDate", title: "创建时间", type: "datetime", width: 190 }
      ],
      tableData4: [],
      queryParamsPage: 1,
      fyTotal: 0,
      pageChecked: false,
      couponcodeList: [],
      use_statusList: [],
      selectionList: []
    };
  },
  watch: {
    "formFields.preparation"(n) {
      this.tableData = [];
      this.MebcouponMakeList.forEach(i => {
        if (n.includes(i.id)) {
          this.tableData.push(i);
        }
      });
    },
    "formFields2.givetype" : {
      handler(n) {
        let vpType = this.getFormOption2("vpType");
        let cardtype = this.getFormOption2("cardtype");
        if (n == 0) {
          vpType.hidden = false;
          cardtype.hidden = true;
          this.HYStatus = false;
        } else if (n == 1) {
          this.HYStatus = true;
          vpType.hidden = true;
          cardtype.hidden = true;
        } else {
          this.HYStatus = false;
          vpType.hidden = true;
          cardtype.hidden = false;
        }
      },
      immediate: true
    }
  },
  methods: {
    getText(l, v) {
      let b = l.filter(i => {
        return i.key == v;
      });
      if (b.length != 0) {
        return b[0].value;
      } else {
        return "";
      }
    },
    changeSelect(selection) {
      this.selectionList = selection;
    },
    selectAll(val) {
      this.selectionList = val;
    },
    handleCurrentChange(val) {
      this.queryParamsPage = val;
      this.getMebCouponhis();
    },
    submit9() {
      if (this.formFields4.opersqrorId == "") {
        this.$Message.error("授权人不能为空");
        return;
      }
      let w = "[]";
      if (
        this.formFields4.preparation == undefined ||
        this.formFields4.preparation == ""
      ) {
        w = "[]";
      } else {
        w = `[{\"name\":\"couponcode\",\"value\":\"${this.formFields4.preparation}\",\"displayType\":\"like\"}]`;
      }
      let params = {
        couponId: this.selectionList.map(i => i.id).join(),
        operatorId: this.formFields4.opersqrorId.join() + ",",
        couponWhere: w,
        couponStatus: this.pageChecked
      };
      this.http.post("/api/MebCouponhis/UpdateOperator", params).then(res => {
        if (res.status) {
          this.$Message.success("操作成功");
          this.model9 = false;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    downLOading() {
      let thead = "<thead><tr><th>姓名</th><th>手机号</th></tr></thead>";
      // 导出表格
      tableToNotIE(thead, "模板");
    },
    getFormOption(field) {
      let option;
      this.formRules.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getFormOption2(field) {
      let option;
      this.formRules2.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getFormOption4(field) {
      let option;
      this.formRules4.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    MebcouponMakeGetPageData() {
      let params = {
        order: "desc",
        page: 1,
        rows: 1000000000,
        sort: "id",
        wheres: `[{\"name\":\"is_generate\",\"value\":\"0\",\"displayType\":\"text\"}]`
      };
      this.http.post("/api/MebcouponMake/getPageData", params).then(res => {
        this.MebcouponMakeList = res.rows;
        let preparation = this.getFormOption("preparation");
        preparation.data = [];
        let ac = [];
        res.rows.forEach(i => {
          let obj = {
            ...i,
            value: i.coupon_name,
            key: i.id
          };
          ac.push(obj);
        });
        preparation.data = ac;
      });

      let param = [
        "MakeCoupon_Status",
        "cardTemplate",
        "Member_Type",
        "coupontype",
        "MebHisUseStatus"
      ];
      this.http.post("/api/Dictionary/GetVueDictionary", param).then(res => {
        res.forEach(i => {
          if (i.dicNo == "MakeCoupon_Status") {
            this.columns.forEach(j => {
              if (j.field == "status") {
                j.bind.data = i.data;
              }
            });
          } else if (i.dicNo == "cardTemplate") {
            let cardtype = this.getFormOption2("cardtype");
            cardtype.data = i.data;
            cardtype.hidden = true;
          } else if (i.dicNo == "Member_Type") {
            let a = this.getFormOption2("vpType");
            a.data = [];
            i.data.forEach(j => {
              let obj = {
                key: j.key,
                label: j.value
              };
              a.data.push(obj);
            });
          } else if (i.dicNo == "coupontype") {
            let b = this.getFormOption4("preparation");
            b.data = i.data;
            // this.columns4[2].bind.data = i.data;
            this.couponcodeList = i.data;
          } else if (i.dicNo == "MebHisUseStatus") {
            // this.columns4[3].bind.data = i.data;
            this.use_statusList = i.data;
          }
        });
      });
    },
    getMebCouponhis(v) {
      let w = "[]";
      if (v == undefined || v == "") {
        w = "[]";
      } else {
        w = `[{\"name\":\"couponcode\",\"value\":\"${v}\",\"displayType\":\"like\"}]`;
      }
      let pahis = {
        order: "desc",
        page: this.queryParamsPage,
        rows: 1000,
        sort: "id",
        wheres: w
      };
      this.http
        .post("/api/MebCouponhis/CouponHisGetPageData", pahis)
        .then(res => {
          this.tableData4 = res.rows;
          this.fyTotal = res.total;
        });
    },
    handleChange(file) {
      const _this = this;
      _this.tableData2 = [];
      const fileName = file.name;
      const reader = new FileReader();
      reader.readAsArrayBuffer(file.raw);
      reader.onload = function() {
        const buffer = reader.result;
        const bytes = new Uint8Array(buffer);
        const length = bytes.byteLength;
        let binary = "";
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        const XLSX = require("xlsx");
        const wb = XLSX.read(binary, {
          type: "binary"
        });
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        let status = outdata.every(i => {
          return i.hasOwnProperty("姓名") || i.hasOwnProperty("手机号");
        });
        const phoneReg = /^1[3456789]\d{9}$/; // 手机号格式校验
        if (status) {
          outdata.forEach(i => {
            let obj = {
              namez: i.姓名,
              phone: i.手机号
            };
            if (phoneReg.test(i.手机号)) {
              _this.tableData2.push(obj);
            } else {
              _this.$Message.error(i.姓名 + "的手机号格式错误，已移除");
            }
          });
        } else {
          _this.$Message.error("格式不正确，请填写姓名、手机号");
        }
      };
    },
    submit() {
      let params = {
        mebmake: this.tableData[0],
        givetype: this.formFields2.givetype,
        dvalue:
          this.formFields2.givetype == 0
            ? this.formFields2.vpType :
            this.formFields2.givetype == 1 ? this.tableData2.map(i => i.phone) : [],
        cardtype: this.formFields2.givetype == 2 ? this.formFields2.cardtype : 0
      };
      this.http.post("/api/MebCoupon/GiveCoupon", params).then(res => {
        if (res.result.status) {
          this.$Message.success(res.result.message);
          this.model = false;
          this.$store.getters.data().viewPageTest.refresh();
        } else {
          this.$Message.error(res.result.message);
        }
      });
    },
    submit3() {
      let param = {
        mainData: {
          ...this.formFields3
        },
        detailData: []
      };
      let params = {
        ...this.formFields3,
        couponid: this.FJGR.couponid
      };
      this.$refs.myform3.validate(() => {
        if (this.HYZHSTATUS) {
          this.http
            .post("/api/SmallUserArchives/AddSmallUser", param)
            .then(res => {
              if (res.status) {
                this.http
                  .post("/api/MebCouponhis/TakeMemberCoupon", params)
                  .then(res => {
                    if (res.status) {
                      this.model3 = false;
                      this.$Message.success("发券成功");
                      this.$store.getters.data().viewPageTest.refresh();
                    } else {
                      this.$Message.error(res.result.message);
                    }
                  });
              }
            });
        } else {
          this.http
            .post("/api/MebCouponhis/TakeMemberCoupon", params)
            .then(res => {
              if (res.status) {
                this.model3 = false;
                this.$Message.success("发券成功");
                this.$store.getters.data().viewPageTest.refresh();
              } else {
                this.$Message.error(res.result.message);
              }
            });
        }
      });
    },
    // 延期
    submit6() {
      let param = {
        mainData: {
          id: this.FJGR.id,
          ...this.formFields6
        }
      };
      this.http.post("/api/MebCouponhis/Recovery", param).then(res => {
        this.$Message.success("延期成功");
        this.model6 = false;
        this.$store.getters.data().viewPageTest.refresh();
      });
    },
    submit7() {
      let param = {
        couponcardid: this.SGHX.id,
        ...this.formFields7
      };
      this.http
        .post("/api/VSmallOrders/CouponCardWriteoff", param)
        .then(res => {
          if (res.status) {
            this.$Message.success("核销成功");
            this.model7 = false;
            this.$store.getters.data().viewPageTest.refresh();
          } else {
            this.$Message.error(res.message);
            this.model7 = true;
          }
        });
    },
    submit8() {
      let param = {
        mainData: {
          id: this.SGHX.id,
          ...this.formFields8
        }
      };
      this.http.post("/api/MebCouponhis/Recovery", param).then(res => {
        this.$Message.success("作废成功");
        this.model8 = false;
        this.$store.getters.data().viewPageTest.refresh();
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.volTable {
  margin: 20px 0;
}
.HYCl {
  .el-button {
    margin-bottom: 20px;
  }
}
.down {
  float: left;
  margin-right: 20px;
}
.upload-demo {
  display: inline-block;
}
</style>
